package com.zy.mc_module.wheel.recyclerview;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

/**
 * author : dq
 * date   : 19/4/22
 * desc   : RecyclerView,滑到底部就加载更多
 */
public abstract class LoadMoresListener extends RecyclerView.OnScrollListener {
    private boolean isScrollUp = false;//是否在往上滑动
    private boolean loading = true;//是否正在加载更多
    private int previousTotal = 0;//每次加载更多后的 新的总item数量

    private int lastVisibleItemPosition;//最后一个可见的item的位置

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        LayoutManager layoutManager = recyclerView.getLayoutManager();
        lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
        int totalItemCount = recyclerView.getAdapter().getItemCount();//item总的个数
        int visibleItemCount = recyclerView.getChildCount();//当前屏幕显示item的数量
        Adapter adapter = recyclerView.getAdapter();
        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            } else if (totalItemCount <= previousTotal && !recyclerView.canScrollVertically(-1)) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && isScrollUp && null != adapter && lastVisibleItemPosition == totalItemCount - 1 && visibleItemCount > 0) {
            //加载更多
            loadMore();
            loading = true;
            previousTotal = totalItemCount;
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        isScrollUp = dy > 0;
    }

    protected abstract void loadMore();
}
